package com.market.service.impl;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.market.dto.ShopCartDto;
import com.market.entity.*;
import com.market.exceptions.MyException;
import com.market.mapper.BuyerMapper;
import com.market.mapper.ShopCartMapper;
import com.market.service.*;
import com.market.utils.SendCode;
import com.market.vo.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @ClassName BuyerServiceImpl
 * @Description 买家
 * @Author pq
 * @Date 2022/3/30 20:46
 * @Version 1.0
 */
@Service
public class BuyerServiceImpl implements BuyerService {
    @Autowired
    BuyerMapper buyerMapper;
    @Autowired
    GoodsService goodsService;
    @Autowired
    BuyerService buyerService;
    @Autowired
    OrderService orderService;
    @Autowired
    BuyerCashFlowService buyerCashFlowService;
    @Autowired
    OrderDetailService orderDetailService;
    @Autowired
    ShopCartService shopCartService;
    @Autowired
    RedisTemplate redisTemplate;
    //todo/ 发送短信验证码并存储
    @Override
    public boolean sendCode(String telephone, HttpServletRequest request) throws IOException {
        SendSmsResponse result=null;
        try {
             result = SendCode.send();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result!=null;
    }

    //todo 买家通过短信验证码注册
    @Override
    public boolean buyerRegisterByCode(Buyer buyer,String code) throws IOException {
        boolean flag=false;
        String redisCode = (String)redisTemplate.opsForValue().get(buyer.getTelephone());
        if(redisCode==null){
            return false;
        }
        if(redisCode.equals(code)){
            flag=true;
        }
        return flag;
    }



    //买家通过账号密码注册
    @Override
    public boolean buyerRegisterByAccountAndPwd(Buyer buyer) throws MyException {
        if(queryBuyerByAccount(buyer.getAccount())==null){
            buyerMapper.buyerRegister(buyer);
            return true;
        }else{
            throw new MyException("该账号已经注册");
        }
    }

    //根据账号查看某个买家
    @Override
    public Buyer queryBuyerByAccount(String account) {
        return buyerMapper.queryBuyerByAccount(account);
    }

    //买家通过账号密码登录
    @Override
    public boolean buyerLoginByAccountAndPwd(String account, String password) throws MyException {
        boolean flag=false;
        Buyer buyer = buyerService.queryBuyerByAccount(account);
        if(buyer==null){
            throw new MyException("该账号不存在");
        }
        if(buyer.getPassword().equals(password)){
            flag=true;
        }
        return flag;
    }

    //todo 买家通过短信验证码登录
    @Override
    public boolean buyerLoginBySmsVerification(String SmsVerificationCode, String telephone) {
        return false;
    }

    //添加买家所在地址
    @Override
    public boolean addBuyerAddress(int buyerId, String address) {
        return buyerMapper.updateBuyerAddress(buyerId,address)>0;
    }

    //修改基本买家信息(昵称，电话号码，地址，性别)
    @Override
    public boolean updateBuyerInfo(Integer buyerId,String nickname,String telephone,String address,String sex) {
        return buyerMapper.updateBuyerInfo(buyerId,nickname,telephone,address,sex)>0;
    }

    //根据商品id查询商品
    @Override
    public Goods queryGoods(int goodsId) {
        return goodsService.queryGoodsByGoodsId(goodsId);
    }

    // 创建空订单
    @Override
    public boolean createOrder(Order order) {
        return orderService.addOrder(order);
    }

    // 确认收货
    @Override
    public boolean confirmReceipt(int orderId) {
        return orderService.updateOrderState(orderId,7);
    }

    //锁定买家
    @Override
    public boolean lockBuyer(int buyerId) {
        return buyerMapper.lockBuyer(buyerId)>0;
    }

    //解锁买家
    @Override
    public boolean unLockBuyer(int buyerId) {
        return buyerMapper.unLockBuyer(buyerId)>0;
    }

    //根据买家id查看买家
    @Override
    public Buyer queryBuyerById(int buyerId) {
        return buyerMapper.queryBuyerById(buyerId);
    }

    @Override
    public List<Buyer> queryAllBuyer() {
        return buyerMapper.queryAllBuyer();
    }

    //todo 买家通过支付宝线上付款
    @Override
    public boolean payByAlipay() {
        return false;
    }

    // 加入购物车
    @Override
    public boolean addToCart(int goodsId, int goodsNum, int buyerId) {
        double sellPrice=goodsService.queryGoodsByGoodsId(goodsId).getPrice();
        ShopCart shopCart=new ShopCart();
        shopCart.setBuyerId(buyerId);
        shopCart.setNums(goodsNum);
        shopCart.setGoodsId(goodsId);
        shopCart.setAmount(sellPrice*goodsNum);
        return shopCartService.addShopCartRecord(shopCart);
    }

    //todo 申请退货(调用退货单的增加退货单记录方法)
    @Override
    public boolean applyReturnGoods(int orderId) {
        return false;
    }

    //todo 申请换货
    @Override
    public boolean applyExchangeGoods(int orderId) {
        return false;
    }



    //根据商品名查找某个商品
    @Override
    public Goods queryGoodsByGoodsName(String goodsName) {
        return goodsService.queryGoodsByGoodsName(goodsName);
    }

    //通过商品类别id查找商品
    @Override
    public List<Goods> queryGoodsByGoodsTypeId(int goodsTypeId) {
        return goodsService.queryGoodsByTypeId(goodsTypeId);
    }

    //充值
    @Override
    public boolean charge(int buyerId,double money) {
        double currentBalance=buyerService.queryBuyerById(buyerId).getBalance();
        double afterChargedBalance=currentBalance+money;
        return buyerMapper.updateBuyerBalance(buyerId,afterChargedBalance)>0;
    }

    //添加订单详情
    @Override
    public boolean addOrderDetail(OrderDetail orderDetail) {
        return orderDetailService.addOrderDetail(orderDetail);
    }

    //买家查看购物车
    @Override
    public List<ShopCartDto> queryShopCartByBuyerId(int buyerId) {

        return shopCartService.findMyShopCart(buyerId);
    }


    // 付款
    @Override
    public boolean pay(int orderId) {
        boolean flag;
        Order order=orderService.queryOrderByOrderId(orderId);
        Buyer buyer=buyerService.queryBuyerById(order.getBuyerId());
        List<OrderDetail> orderDetails = orderDetailService.queryOrderDetailByOrderId(orderId);
        int buyNum=0;
        double goodsPrice=0;
        for (OrderDetail orderDetail : orderDetails) {
             buyNum+=orderDetail.getBuyNum();
             goodsPrice+=orderDetail.getGoodsPrice();
        }
        double actualPayment=buyNum*goodsPrice;
        double currentBalance=buyer.getBalance();
        double newBalance=currentBalance-actualPayment;
        BuyerCashFlow buyerCashFlow=new BuyerCashFlow();
        if(newBalance>=0){
            //修改买家账户余额
            buyerMapper.updateBuyerBalance(buyer.getId(),newBalance);
            //增加买家流水记录
            Date date=new Date();
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
            String payTime=sdf.format(date);
            buyerCashFlow.setBuyerId(buyer.getId());
            buyerCashFlow.setOrderCode(order.getOrderCode());
            buyerCashFlow.setAmount(actualPayment);
            buyerCashFlow.setTypes(2);//（1表示充值2表示购买3表示退货）
            buyerCashFlow.setTradeTime(date);
            buyerCashFlowService.addBuyerCashFlow(buyerCashFlow);
            //订单状态修改为已支付状态
            orderService.updateOrderState(orderId,1);
            //为订单添加付款时间
            orderService.updateOrderPayTime(orderId,payTime);
            //为订单添加实付金额
            orderService.updateActualPay(actualPayment,orderId);
            flag=true;
        }else{
            flag=false;
        }
        return flag;
    }

    //根据小店id查看买家
    @Override
    public List<Buyer> queryBuyerByStoreId(int storeId) {
        return buyerMapper.queryBuyerByStoreId(storeId);
    }

    //添加小店id
    @Override
    public boolean addStoreId(int buyerId,int storeId) {
        Buyer buyer = buyerService.queryBuyerById(buyerId);
        if (buyer.getStoreId() == null) {
            return buyerMapper.addStoreId(buyerId, storeId)==1;
        }
            return false;
    }



}
